package com.wft.design.oauth.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wft.design.common.core.util.JsonUtils;
import com.wft.design.common.security.bean.Authentication;
import com.wft.design.common.security.exception.AuthenticationException;
import com.wft.design.oauth.service.RefreshTokenService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @author WFT
 * @date 2019/12/30
 * description:
 */
@Service
public class RefreshTokenServiceImpl implements RefreshTokenService {

    /**
     * Jwt Token 颁发者
     */
    private final static String ISSUER = "http://www.cjlgb.com";

    /**
     * 算法
     */
    private final static Algorithm ALGORITHM = Algorithm.HMAC256(ISSUER);

    /**
     * 凭证信息
     */
    private final static String CERT = "cert";

    /**
     * 刷新令牌的有效期为30天
     */
    private final static long REFRESH_TOKEN_VALIDITY = 1000L * 60 * 60 * 24 * 30;

    @Override
    public String generateRefreshToken(Authentication authentication) {
        return JWT.create().withIssuer(ISSUER)
                //  Jwt唯一标识
                .withJWTId(UUID.randomUUID().toString())
                //  认证信息
                .withClaim(CERT, JsonUtils.toJson(authentication))
                //  有效期
                .withExpiresAt(new Date(System.currentTimeMillis() + REFRESH_TOKEN_VALIDITY))
                .sign(ALGORITHM);
    }

    @Override
    public Authentication getAuthentication(String refreshToken) {
        try {
            //  验证 Jwt Token 的颁发者,有效期
            DecodedJWT jwt = JWT.require(ALGORITHM).withIssuer(ISSUER).build().verify(refreshToken);
            //  将凭证信息序列化成对象
            return JsonUtils.toBean(jwt.getClaim(CERT).asString(),Authentication.class);
        }catch (JWTVerificationException e){
            throw new AuthenticationException(e.getMessage());
        }
    }
}
